﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Threading;
using Microsoft.Extensions.Logging;
using BarcodeParserBuilder;

namespace UDIAdapter.Services
{
    public class BarcodeService
    {

        public SerialPort SerialPort;

        //private Thread readThread;

        // [Inject]
        private readonly ILogger<BarcodeService> Logger;

        public BarcodeService(ILogger<BarcodeService> Logger)
        {
            this.Logger = Logger;

            SerialPort = new SerialPort();

            string[] names = SerialPort.GetPortNames();

            Logger.LogInformation("所有串口:");
            for (int i = 0; i < names.Length; i++) 
            {
                Logger.LogInformation(names[i]);
            }
            Logger.LogInformation("---------------------");

            SerialPort.PortName = "COM3";
            SerialPort.BaudRate = 9600;
            SerialPort.Parity = Parity.None;
            SerialPort.StopBits = StopBits.One;
            SerialPort.DataBits = 8;
            SerialPort.Handshake = Handshake.None;
            SerialPort.RtsEnable = true;

            SerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            SerialPort.Open();

        }

        public void Read()
        {
            while (true)
            {
                try
                {
                    string message = SerialPort.ReadLine();
                    Logger.LogInformation(message);
                }
                catch (TimeoutException) { }
            }
        }

        private void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadLine();
            Logger.LogInformation("Data Received:");
            Logger.LogInformation(indata);

            bool isSuccessful = ParserBuilder.TryParse(indata, out Barcode barcode);

            if (isSuccessful)
            {
            }
            else 
            {
                
            }
        }

    }
}
